package com.example.hosptial.newController;

import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.model.view.WardBedPatientView;
import com.example.hosptial.model.view.WardStatusView;
import com.example.hosptial.service.BedTransferService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 病床转移控制器
 */
@Controller
@RequestMapping("/doctor/bed-transfer")
@RequiredArgsConstructor
public class BedTransferController {

    private static final Logger logger = LoggerFactory.getLogger(BedTransferController.class);
    private final BedTransferService bedTransferService;

    /**
     * 显示病床转移主页面
     */
    @GetMapping
    public String showTransferPage(HttpSession session) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return "redirect:/doctor/auth/login";
        }
        return "doctor/bed-transfer";
    }

    /**
     * 获取指定楼层的病房列表
     */
    @GetMapping("/wards")
    @ResponseBody
    public ResponseEntity<?> getAvailableWards(
            @RequestParam(required = false) Integer floorNum,
            HttpSession session) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).body(Map.of(
                "code", 401,
                "message", "未登录或会话已过期"
            ));
        }

        try {
            List<?> result;
            if (floorNum == null) {
                // 如果没有指定楼层，返回楼层列表
                result = bedTransferService.getFloorsByDeptId(doctor.getDeptId());
            } else {
                // 如果指定了楼层，返回该楼层的病房列表
                result = bedTransferService.getAvailableWardsByDeptIdAndFloor(doctor.getDeptId(), floorNum);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取病房列表失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(Map.of(
                "code", 500,
                "message", "获取病房列表失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取指定病房的可用床位
     */
    @GetMapping("/beds")
    @ResponseBody
    public ResponseEntity<?> getAvailableBeds(@RequestParam Integer wardId) {
        try {
            List<WardBedPatientView> beds = bedTransferService.getAvailableBedsByWardId(wardId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", beds);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取床位列表失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(Map.of(
                "code", 500,
                "message", "获取床位列表失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 执行病床转移
     */
    @PostMapping("/transfer")
    @ResponseBody
    public ResponseEntity<?> transferBed(
            @RequestParam Integer patientId,
            @RequestParam Integer newBedId,
            HttpSession session) {
        
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).body(Map.of(
                "code", 401,
                "message", "未登录或会话已过期"
            ));
        }

        try {
            bedTransferService.transferBed(patientId, newBedId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "换床成功");
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException | IllegalStateException e) {
            logger.warn("换床失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of(
                "code", 400,
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            logger.error("换床失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "换床失败: " + e.getMessage()
            ));
        }
    }
}